﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Security.Cryptography;
using System.IO;
using System.Text;

using CE.Global;
using CE.Image;
using CE.User;
using CE.Mail;
using CE.Database;

public partial class user_unsubscribe : MyLanguageBasePage
{
    protected override void InitializeCulture()
    {
        String selectedCulture = CE.Global.General.SetCulture();
        base.InitializeCulture();
    }

    string _redirectUrl = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        Master.Page.Title = Resources.Title.UnsubscribeTitle;
        if (Session["ImageCount"] != null)
        {
            if (Convert.ToInt32(Session["ImageCount"].ToString()) > 5)
            {
                btnSubmit.Enabled = false;
                btnNewImage.Enabled = false;
                txtEmail.Enabled = false;
                txtSecurityCode.Enabled = false;
                Response.Redirect("user-message?mt=UM&ec=1993");
            }
            else
            {
                btnSubmit.Enabled = true;
                btnNewImage.Enabled = true;
                txtEmail.Enabled = true;
                txtSecurityCode.Enabled = true;
            }
        }

        if (!Page.IsPostBack)
        {
            txtEmail.Text = "";
            txtEmail.ReadOnly = false;
            Uri theRealURL = new Uri(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.RawUrl);
            if (HttpUtility.ParseQueryString(theRealURL.Query).Keys.Count > 0)
            {
                string rq_uid = HttpUtility.ParseQueryString(theRealURL.Query).Get("uid");
                if (rq_uid != null && rq_uid != string.Empty)
                {
                    CXDecryption.Decryption cxd = new CXDecryption.Decryption();
                    txtEmail.Text = cxd.Decrypt(rq_uid).Trim().ToLower();
                    if (txtEmail.Text.Trim() != string.Empty)
                    {
                        txtEmail.ReadOnly = true;
                    }
                }
            }

            Session["UMMSG"] = null;
            LogUserViewedHistory();

            if (Session["ImageCount"] != null)
            {
                if (Convert.ToInt32(Session["ImageCount"].ToString()) <= 5)
                {
                    CreateUpdateImageAndSession();
                }
            }
            else
            {
                CreateUpdateImageAndSession();
            }
            txtEmail.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtEmail.ClientID + "','" + rfvEmail.ClientID + "','" + revEmail.ClientID + "');");
            txtSecurityCode.Attributes.Add("onblur", "ShowValidationEffect('" + txtSecurityCode.ClientID + "','" + rfvSecurityCheck.ClientID + "');");

        }
    }

    private void LogUserViewedHistory()
    {
        UserViewHistoryDB _userviewdb = new UserViewHistoryDB();
        _userviewdb.LogViewedHistory("PWR", Request, "User password recovery.");
    }

    private void CreateUpdateImageAndSession()
    {
        MyImage myimage = new MyImage();
        string salt = "";

        if (Session[CE.Global.General.SecurityCheckWord] != null)
        {
            salt = myimage.GetRandomWord(Session[CE.Global.General.SecurityCheckWord].ToString());
        }
        else
        {
            if (Session[CE.Global.General.SecurityCheckWord] != null)
            {
                salt = myimage.GetRandomWord(Session[CE.Global.General.SecurityCheckWord].ToString());
            }
            else
            {
                salt = myimage.GetRandomWord("all");
            }
        }
        Session[CE.Global.General.SecurityCheckWord] = salt;
        imgCAPTCHA.ImageUrl = @"/CAPTCHA/CAPTCHAImageHandler.ashx?id=" + CE.Security.MySecurity.Encrypt(salt, true);
        txtSecurityCode.Text = "";
    }

    protected void btnNewImage_Click(object sender, EventArgs e)
    {
        CreateUpdateImageAndSession();
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            ChangeValidationEffectServerSide("customer");
            Page.Validate("customer");
            if (Page.IsValid)
            {
                if (Session[CE.Global.General.SecurityCheckWord] != null)
                {
                    string _usrText = txtSecurityCode.Text.ToUpper();
                    string _imgText = Session[CE.Global.General.SecurityCheckWord].ToString().ToUpper();
                    if (_usrText == _imgText)
                    {
                        if (Unsubscribe(txtEmail.Text.Trim().ToLower(), 3, "User Unsubscribe from GG website") > 0)
                        {
                            _redirectUrl = CE.Global.General.GetUrl("~/user/user-message", Page);
                            Session["UMMSG"] = "UMG,200";
                            Response.Redirect(_redirectUrl);
                        }
                        else
                        {
                            lblMessage.Text = Resources.ErrorMessage.EmailFail;
                        }
                    }
                    else
                    {
                        lblMessage.Text = Resources.UserMessage.WrongSecurityCheck;
                        CreateUpdateImageAndSession();
                    }
                }
                else
                {
                    lblMessage.Text = Resources.ErrorMessage.SecurityCodeExpired;
                    CreateUpdateImageAndSession();
                }
            }
        }
        catch (Exception ex)
        {
        }
    }

    public string CreateSalt(int size)
    {
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        Byte[] buff = new Byte[size];
        rng.GetBytes(buff);

        return Convert.ToBase64String(buff);
    }

    private void ChangeValidationEffectServerSide(string strValidationGroup)
    {
        txtEmail.Text = HttpUtility.HtmlEncode(txtEmail.Text);
        txtSecurityCode.Text = HttpUtility.HtmlEncode(txtSecurityCode.Text);

        //Email
        if (rfvEmail.Enabled && rfvEmail.ValidationGroup == strValidationGroup)
        {
            rfvEmail.Validate();
            if (rfvEmail.IsValid == false)
            {
                txtEmail.ControlStyle.CssClass = "input-fields validationError";
            }
            else
            {
                txtEmail.ControlStyle.CssClass = "input-fields";
            }
        }
        else
        {
            txtEmail.ControlStyle.CssClass = "input-fields";
        }

        if (revEmail.Enabled && revEmail.ValidationGroup == strValidationGroup)
        {
            if (rfvEmail.IsValid)
            {
                revEmail.Validate();
                if (revEmail.IsValid == false)
                {
                    txtEmail.ControlStyle.CssClass = "input-fields validationError";
                }
                else
                {
                    txtEmail.ControlStyle.CssClass = "input-fields";
                }
            }
        }
        else
        {
            txtEmail.ControlStyle.CssClass = "input-fields";
        }

        //Feed back
        if (rfvSecurityCheck.Enabled && rfvSecurityCheck.ValidationGroup == strValidationGroup)
        {
            rfvSecurityCheck.Validate();
            if (rfvSecurityCheck.IsValid == false)
            {
                txtSecurityCode.ControlStyle.CssClass = "input-fields validationError";
            }
            else
            {
                txtSecurityCode.ControlStyle.CssClass = "input-fields";
            }
        }
        else
        {
            txtSecurityCode.ControlStyle.CssClass = "input-fields";
        }

    }

    public Int64 Unsubscribe(string Email, Int64 EDM, string EDMType)
    {
        MyDatabase _db = new MyDatabase();
        Int64 _result = -1;
        string _spName = "sprocUnsubscribeEmailInsertUpdateSingleItem";

        SortedList _sPara = new SortedList();

        #region Parameter
        _sPara.Add("@Email", Email);
        _sPara.Add("@EDM", EDM);
        _sPara.Add("@EDMType", EDMType);
        #endregion

        _result = _db.ExecuteSP(_spName, _sPara);

        return _result;
    }

}
